<template>
  <div class="inner-container">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
      <el-form-item label="文章类别" prop="categoryId">
        <el-select v-model="formData.categoryId" placeholder="请选择文章类别" style="width: 100%">
          <el-option v-for="item in categoryList" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入文章标题"/>
      </el-form-item>
      <el-form-item label="文章封面" prop="coverUrl">
        <el-upload
            class="avatar-uploader"
            action="https://run.mocky.io/v3/ef3245ec-770d-4e7a-add0-c1b3565ccbde"
            :show-file-list="false"
            :before-upload="beforePictureUpload"
            :on-success="handlePictureSuccess"
        >
          <img v-if="formData.coverUrl" :src="formData.coverUrl" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="关键词" prop="keywords">
        <el-input v-model="formData.keywords" placeholder="各关键词使用英文的逗号分隔"/>
      </el-form-item>
      <el-form-item label="排序序号" prop="sort">
        <el-input v-model="formData.sort" type="number" placeholder="排序序号，0-255之间的整数"/>
      </el-form-item>
      <el-form-item label="审核状态" prop="checkState">
        <el-radio-group v-model="formData.checkState">
          <el-radio :label="0">未审核</el-radio>
          <el-radio :label="1">通过</el-radio>
          <el-radio :label="2">驳回</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="显示状态" prop="isDisplay">
        <el-switch v-model="formData.isDisplay" :active-value="1" :inactive-value="0"/>
      </el-form-item>
      <el-form-item label="是否推荐" prop="isRecommend">
        <el-switch v-model="formData.isRecommend" :active-value="1" :inactive-value="0"/>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div style="width: 100%; border: 1px solid #dcdfe6">
          <Toolbar :editor="editorRef" style="border-bottom: 1px solid #dcdfe6"/>
          <Editor :defaultConfig="editorConfig" @onCreated="handleCreated" style="height: 300px"/>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">确定</el-button>
        <el-button @click="$router.push('/content/article')">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {onBeforeUnmount, onMounted, ref, shallowRef} from 'vue'
import {ElMessage} from 'element-plus'
import router from '@/router'
import request from '@/utils/request'
import '@wangeditor/editor/dist/css/style.css'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

// --------------------------------------------------
const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
const editorConfig = { placeholder: '请输入内容...' }
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor != null) editor.destroy()
})

// --------------------------------------------------
const formRef = ref()
const formData = ref({
  id: undefined,
  authorId: undefined,
  categoryId: undefined,
  title: undefined,
  brief: undefined,
  content: undefined,
  coverUrl: undefined,
  keywords: undefined,
  sort: undefined,
  checkState: 0,
  isDisplay: 0,
  isRecommend: 0
})
const formRules = ref({
  categoryId: [
    {required: true, message: '请选择文章类别'}
  ],
  title: [
    {required: true, message: '请填写文章标题'}
  ],
  sort: [
    {required: true, message: '请填写排序序号'}
  ],
  content: [
    {required: true, message: '请填写文章内容'}
  ]
})

const formReset = () => {
  formData.value = {
    id: undefined,
    authorId: undefined,
    categoryId: undefined,
    title: undefined,
    brief: undefined,
    content: undefined,
    coverUrl: undefined,
    keywords: undefined,
    sort: undefined,
    checkState: 0,
    isDisplay: 0,
    isRecommend: 0
  }
  formRef.value.resetFields()
  editorRef.value.setHtml('')
}

const saveOrUpdate = () => {
  formData.value.content = undefined
  let editorText = editorRef.value.getText()
  if (editorText) {
    formData.value.brief = editorText.slice(0, 30)
    formData.value.content = editorRef.value.getHtml()
  }
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请正确填写参数')
      return false
    }
    console.log(formData.value)
    let operate = formData.value.id ? 'update' : 'add-new'
    request.post(
        `/content/article/${operate}`, formData.value)
        .then(res => {
          ElMessage.success('保存成功')
          formReset()
        })
  })
}

const beforePictureUpload = (rawFile) => {
  if (rawFile.type.indexOf('image/') === -1) {
    ElMessage.error('请选择图片文件')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('上传图片大小不能超过10MB')
    return false
  }
  return true
}

const handlePictureSuccess = (response, uploadFile) => {
  //formData.value.coverUrl = response.data
  formData.value.coverUrl = URL.createObjectURL(uploadFile.raw)
}

const categoryList = ref([])
const getCategoryList = () => {
  request.get('/content/category/list')
      .then(res => {
        categoryList.value = res.data.list
      })
}

const getDataById = () => {
  let id = router.currentRoute.value.query.id
  if (id && id.length > 0) {
    request.get(`/content/article/${id}`)
        .then(res => {
          formData.value = res.data
          editorRef.value.setHtml(res.data.content)
        })
  }
}

// --------------------------------------------------
onMounted(() => {
  getCategoryList()
  getDataById()
})
</script>

<style scoped>
.avatar-uploader {
  width: 128px;
  height: 128px;
  position: relative;
  overflow: hidden;
  border-radius: 6px;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader .avatar {
  width: 128px;
  height: 128px;
  display: block;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  text-align: center;
}
</style>
